package pl.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.example.domain.Car;
import pl.example.domain.Color;
import pl.example.domain.Earing;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class GoogleEngineHelloWorldServlet extends HttpServlet {

	static {
		ObjectifyService.register(Color.class);
		ObjectifyService.register(Earing.class);
		ObjectifyService.register(Car.class);
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		PrintWriter writer = resp.getWriter();
		earingExample(writer);

	}

	private void earingExample(PrintWriter writer) {
		// local cache
		// ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		Objectify ofy = ObjectifyService.begin();

		// nowy kolor
		Color color = new Color("Kolor zielony. ");
		save(ofy, color);
		Color foundColor = (Color) find(ofy, color.getClass(), color.getId());

		// nowy kolczyk
		Earing earing = new Earing("Kolczyk ladny. ");
		save(ofy, earing);
		Earing found = (Earing) find(ofy, earing.getClass(), earing.getId());

		// polaczenie...
		color.addEaring(earing);

		save(ofy, color);
		Color foundColor2 = (Color) find(ofy, color.getClass(), color.getId());

		ArrayList<Key<Earing>> products = foundColor2.getProducts();
		Key<Earing> key = products.get(0);
		System.out.println("Earing key: " + key);

	}

	private Object find(Objectify ofy, Class clazz, Long id) {
		Object object = ofy.get(clazz, id);
		System.out.println("Found: " + object);
		return object;
	}

	private void save(Objectify ofy, Object o) {
		System.out.println("Saving: " + o.toString());
		ofy.put(o);
	}

	private void useObjectify(PrintWriter printWriter) {

		Objectify ofy = ObjectifyService.begin();

		// Simple create
		Car porsche = new Car("2FAST");
		ofy.put(porsche);

		printWriter.println("porsche id = " + porsche.id);

		// Get it back
		Car fetched1 = ofy.get(new Key<Car>(Car.class, porsche.id));
		Car fetched2 = ofy.get(Car.class, porsche.id); // equivalent, more
														// convenient

		printWriter.println("Fetched porsche id i vid " + fetched2.id + " "
				+ fetched2.vin);
	}
}
